<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <base href="<%=basePath%>"/>
    <title>茶叶进销存系统 - 查看采购单</title>
    <link rel="stylesheet" href="css/global.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <style>
        .form-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--text-regular);
        }
        .form-control {
            width: 100%;
            padding: 10px 15px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            font-size: 14px;
            transition: all 0.3s;
            background-color: #fff;
        }
        .form-control:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 2px rgba(139, 158, 107, 0.2);
        }
        .btn-group {
            display: flex;
            justify-content: flex-end;
            gap: 15px;
            margin-top: 30px;
        }
        .tea-icon {
            color: var(--primary-color);
            margin-right: 5px;
        }
        .form-header {
            font-size: 18px;
            color: var(--text-regular);
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid var(--border-color);
        }
        .form-row {
            display: flex;
            gap: 20px;
        }
        .form-col {
            flex: 1;
        }
        .purchase-item {
            background: #f8f9fa;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 15px;
            position: relative;
        }
        .item-remove-btn {
            position: absolute;
            top: 10px;
            right: 10px;
            background: var(--danger-color);
            color: white;
            border: none;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .total-summary {
            background: var(--primary-color);
            color: white;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
            margin-bottom: 20px;
        }
        .total-amount {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        .item-subtotal {
            font-weight: bold;
            color: var(--success-color);
        }
        .purchase-info {
            background: var(--bg-color);
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .purchase-info .info-item {
            display: inline-block;
            margin-right: 20px;
            color: var(--text-regular);
        }
        .purchase-info .info-label {
            font-weight: bold;
            color: var(--text-secondary);
        }
    </style>
</head>
<body>
<div class="app-container">
    <!-- 侧边栏 -->
    <div class="sidebar" id="sidebar">
        <div class="sidebar-logo" onclick="toggleSidebar()">
            <span><i class="fas fa-leaf tea-icon"></i> 茶叶进销存系统</span>
        </div>

        <div class="sidebar-menu">
            <div
                    class="menu-item "
                    onclick="location.href='views/home.jsp'"
            >
                <i class="fas fa-home"></i>
                <span>系统首页</span>
            </div>
            <div class="menu-item" onclick="location.href='TeaServlet'">
                <i class="fas fa-coffee"></i>
                <span>茶叶管理</span>
            </div>
            <div class="menu-item" onclick="location.href='CategoryServlet'">
                <i class="fas fa-tags"></i>
                <span>分类管理</span>
            </div>
            <div class="menu-item" onclick="location.href='WarehouseServlet'">
                <i class="fas fa-boxes"></i>
                <span>仓库管理</span>
            </div>
            <div class="menu-item" onclick="location.href='OrderServlet'">
                <i class="fas fa-receipt"></i>
                <span>订单管理</span>
            </div>
            <div class="menu-item" onclick="location.href='LogisticsServlet'">
                <i class="fas fa-shipping-fast"></i>
                <span>物流管理</span>
            </div>
            <div class="menu-item" onclick="location.href='SupplierServlet'">
                <i class="fas fa-truck"></i>
                <span>供应商管理</span>
            </div>
            <div class="menu-item active" onclick="location.href='<%=basePath%>purchase/list'">
                <i class="fas fa-truck"></i>
                <span>采购管理</span>
            </div>
            <div class="menu-item" onclick="location.href='CustomerServlet'">
                <i class="fas fa-users"></i>
                <span>客户管理</span>
            </div>
            <div class="menu-item" onclick="location.href='AddressServlet'">
                <i class="fas fa-map-marker-alt"></i>
                <span>地址管理</span>
            </div>
        </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <div class="navbar">
            <div class="navbar-left">
                <h3><i class="fas fa-eye tea-icon"></i> 查看采购单</h3>
            </div>
            <div class="navbar-right">
                <span><i class="fas fa-user tea-icon"></i> 欢迎，${ username}管理员</span>
                <a href="LogoutServlet" class="el-link el-link--danger ml-10"><i class="fas fa-sign-out-alt"></i> 退出</a>
            </div>
        </div>

        <div class="el-card">
            <div class="el-card__header">
                <span><i class="fas fa-info-circle tea-icon"></i> 查看采购单信息</span>
            </div>
            <div class="el-card__body">
                <!-- 采购单基本信息，保持不变 -->
                <div class="purchase-info">
                    <div class="info-item">
                        <span class="info-label">采购单号：</span>
                        <span>${purchase.purchase_no}</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">状态：</span>
                        <span class="el-tag el-tag--warning">待审核</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">采购单ID：</span>
                        <span>#${purchase.purchase_id}</span>
                    </div>
                </div>

                <form action="purchase/update" method="post" class="form-container" id="purchaseForm">
                    <input type="hidden" name="purchaseId" value="${purchase.purchase_id}">

                    <div class="form-header">
                        <i class="fas fa-info-circle tea-icon"></i> 基本信息
                    </div>

                    <div class="form-row">
                        <div class="form-col">
                            <div class="form-group">
                                <label><i class="fas fa-truck tea-icon"></i> 供应商</label>
                                <input type="text" class="form-control" value="${purchase.supplier.supplier_name}" readonly>
                            </div>
                        </div>
                        <div class="form-col">
                            <div class="form-group">
                                <label><i class="fas fa-warehouse tea-icon"></i> 入库仓库</label>
                                <input type="text" class="form-control" value="${purchase.warehouse.warehouse_name}" readonly>
                            </div>
                        </div>
                    </div>

                    <!-- 金额汇总，保持不变 -->
                    <div class="total-summary">
                        <div class="total-amount" id="totalAmount">¥<fmt:formatNumber value="${purchase.total_amount}" pattern="#,##0.00"/></div>
                        <div>共 <span id="itemCount">${purchaseItems.size()}</span> 个采购项目</div>
                    </div>

                    <div class="form-header">
                        <i class="fas fa-list tea-icon"></i> 采购项目
                        <!-- 隐藏添加项目按钮 -->
                    </div>

                    <div id="purchaseItems">
                        <!-- 现有采购项目，表单元素设为只读 -->
                        <c:forEach items="${purchaseItems}" var="item" varStatus="status">
                            <div class="purchase-item" id="item-${status.index}">
                                <button type="button" class="item-remove-btn" onclick="removePurchaseItem(${status.index})" title="删除项目" style="display: none;">
                                    <i class="fas fa-times"></i>
                                </button>
                                <div class="form-row">
                                    <div class="form-col">
                                        <div class="form-group">
                                            <label>茶叶</label>
                                            <input type="text" class="form-control" value="${item.tea.tea_name}" readonly>
                                        </div>
                                    </div>
                                    <div class="form-col">
                                        <div class="form-group">
                                            <label>数量</label>
                                            <input type="number" name="quantity" class="form-control"
                                                   min="0.01" step="0.01" value="${item.quantity}"
                                                   onchange="calculateSubtotal(${status.index})" readonly>
                                        </div>
                                    </div>
                                    <div class="form-col">
                                        <div class="form-group">
                                            <label>单价</label>
                                            <input type="number" name="unitPrice" class="form-control"
                                                   min="0.01" step="0.01" value="${item.unit_price}"
                                                   onchange="calculateSubtotal(${status.index})" readonly>
                                        </div>
                                    </div>
                                    <div class="form-col">
                                        <div class="form-group">
                                            <label>小计</label>
                                            <div class="form-control item-subtotal" id="subtotal-${status.index}">¥<fmt:formatNumber value="${item.quantity * item.unit_price}" pattern="#,##0.00"/></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </c:forEach>
                    </div>

                    <div id="emptyMessage" style="text-align: center; padding: 40px 0; color: var(--text-secondary); display: none;">
                        <i class="fas fa-inbox" style="font-size: 36px; margin-bottom: 15px; opacity: 0.5;"></i>
                        <p>暂无采购项目，点击"添加项目"按钮开始添加</p>
                    </div>

                    <div class="btn-group">
                        <button type="button" class="el-button" onclick="history.back()">
                            <i class="fas fa-arrow-left"></i> 返回列表
                        </button>
                        <!-- 隐藏保存修改按钮 -->
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>


<script>
    let isCollapsed = false;
    let itemIndex = ${purchaseItems.size()};

    const teas = [
        <c:forEach items="${teas}" var="tea" varStatus="status">
        {
            id: ${tea.tea_id},
            name: '${tea.tea_name}',
            price: ${tea.price},
            unit: '${tea.unit}'
        }<c:if test="${!status.last}">,</c:if>
        </c:forEach>
    ];

    function toggleSidebar() {
        const sidebar = document.getElementById('sidebar');
        isCollapsed = !isCollapsed;
        sidebar.classList.toggle('collapsed', isCollapsed);
        localStorage.setItem('sidebarCollapsed', isCollapsed);
    }

    function addPurchaseItem() {
        const itemsContainer = document.getElementById('purchaseItems');
        const emptyMessage = document.getElementById('emptyMessage');

        const itemHtml = '<div class="purchase-item" id="item-' + itemIndex + '">' +
            '<button type="button" class="item-remove-btn" onclick="removePurchaseItem(' + itemIndex + ')" title="删除项目">' +
            '<i class="fas fa-times"></i>' +
            '</button>' +
            '<div class="form-row">' +
            '<div class="form-col">' +
            '<div class="form-group">' +
            '<label>茶叶</label>' +
            '<select name="teaId" class="form-control" onchange="updateItemPrice(' + itemIndex + ')" required>' +
            '<option value="">请选择茶叶</option>' +
            teas.map(function(tea) { return '<option value="' + tea.id + '" data-price="' + tea.price + '" data-unit="' + tea.unit + '">' + tea.name + '</option>'; }).join('') +
            '</select>' +
            '</div>' +
            '</div>' +
            '<div class="form-col">' +
            '<div class="form-group">' +
            '<label>数量</label>' +
            '<input type="number" name="quantity" class="form-control" min="0.01" step="0.01" placeholder="0.00" onchange="calculateSubtotal(' + itemIndex + ')" required>' +
            '</div>' +
            '</div>' +
            '<div class="form-col">' +
            '<div class="form-group">' +
            '<label>单价</label>' +
            '<input type="number" name="unitPrice" class="form-control" min="0.01" step="0.01" placeholder="0.00" onchange="calculateSubtotal(' + itemIndex + ')" required>' +
            '</div>' +
            '</div>' +
            '<div class="form-col">' +
            '<div class="form-group">' +
            '<label>小计</label>' +
            '<div class="form-control item-subtotal" id="subtotal-' + itemIndex + '">¥0.00</div>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';

        itemsContainer.insertAdjacentHTML('beforeend', itemHtml);
        emptyMessage.style.display = 'none';
        itemIndex++;
        updateItemCount();
    }

    function updateItemPrice(index) {
        const itemRow = document.getElementById('item-' + index);
        const teaSelect = itemRow.querySelector('select[name="teaId"]');
        const unitPriceInput = itemRow.querySelector('input[name="unitPrice"]');

        const selectedOption = teaSelect.options[teaSelect.selectedIndex];
        if (selectedOption.value) {
            const price = selectedOption.getAttribute('data-price');
            unitPriceInput.value = parseFloat(price).toFixed(2);
            calculateSubtotal(index);
        }
    }

    function calculateSubtotal(index) {
        const itemRow = document.getElementById('item-' + index);
        const quantityInput = itemRow.querySelector('input[name="quantity"]');
        const unitPriceInput = itemRow.querySelector('input[name="unitPrice"]');
        const subtotalDiv = document.getElementById('subtotal-' + index);

        const quantity = parseFloat(quantityInput.value) || 0;
        const unitPrice = parseFloat(unitPriceInput.value) || 0;
        const subtotal = quantity * unitPrice;

        subtotalDiv.textContent = '¥' + subtotal.toFixed(2);
        calculateTotal();
    }

    function calculateTotal() {
        const itemsContainer = document.getElementById('purchaseItems');
        const items = itemsContainer.children;
        let total = 0;

        for (let i = 0; i < items.length; i++) {
            const item = items[i];
            const quantityInput = item.querySelector('input[name="quantity"]');
            const unitPriceInput = item.querySelector('input[name="unitPrice"]');

            const quantity = parseFloat(quantityInput.value) || 0;
            const unitPrice = parseFloat(unitPriceInput.value) || 0;
            total += quantity * unitPrice;
        }

        document.getElementById('totalAmount').textContent = '¥' + total.toFixed(2);
    }

    function removePurchaseItem(index) {
        const itemRow = document.getElementById('item-' + index);
        itemRow.remove();

        updateItemCount();
        calculateTotal();

        const itemsContainer = document.getElementById('purchaseItems');
        const emptyMessage = document.getElementById('emptyMessage');
        if (itemsContainer.children.length === 0) {
            emptyMessage.style.display = 'block';
        }
    }

    function updateItemCount() {
        const itemsContainer = document.getElementById('purchaseItems');
        const count = itemsContainer.children.length;
        document.getElementById('itemCount').textContent = count;
    }

    window.onload = function() {
        const savedState = localStorage.getItem('sidebarCollapsed');
        if(savedState === 'true') {
            document.getElementById('sidebar').classList.add('collapsed');
            isCollapsed = true;
        }

        document.getElementById('purchaseForm').addEventListener('submit', function(e) {
            const itemsContainer = document.getElementById('purchaseItems');
            if (itemsContainer.children.length === 0) {
                e.preventDefault();
                alert('请至少添加一个采购项目');
                return false;
            }

            const items = itemsContainer.children;
            for (let i = 0; i < items.length; i++) {
                const item = items[i];
                const teaSelect = item.querySelector('select[name="teaId"]');
                const quantityInput = item.querySelector('input[name="quantity"]');
                const unitPriceInput = item.querySelector('input[name="unitPrice"]');

                if (!teaSelect.value || !quantityInput.value || !unitPriceInput.value) {
                    e.preventDefault();
                    alert('请完整填写所有采购项目信息');
                    return false;
                }
            }
        });
    }
</script>
</body>
</html>
